<!--
 * @Descripttion: (政策/lay_policy)
 * @Author: (admin)
 * @Date: (2024-09-28)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" />
      </el-form-item>
      <!-- <el-form-item label="商家" prop="companyId">
        <el-select clearable multiple v-model="queryParams.companyId" placeholder="请选择商家">
          <el-option v-for="item in  options.sql_company " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
            <span class="fl">{{ item.dictLabel }}</span>
            <span class="fr" style="color: var(--el-text-color-secondary);">{{ item.dictValue }}</span>          
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['laypolicy:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['laypolicy:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['laypolicy:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table v-if="refreshTable" :data="dataList" v-loading="loading" ref="tableRef" border highlight-current-row
      @selection-change="handleSelectionChange" :default-expand-all="isExpandAll" row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="name" label="名称" width="350" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="sort" label="序号" width="60" align="center" />
      <!-- <el-table-column prop="titile" label="标题" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column prop="icon" label="图标" align="center">
        <template #default="scope">
          <ImagePreview :src="scope.row.icon"></ImagePreview>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="imageUrl" label="图片" align="center">
        <template #default="scope">
          <ImagePreview :src="scope.row.imageUrl"></ImagePreview>
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="parentId" label="上级id" align="center" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column prop="status" width="70" label="状态" align="center">
        <template #default="scope">
          <dict-tag :options="options.status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="companyId" label="商家" align="center" :show-overflow-tooltip="true" /> -->

      <el-table-column prop="createTime" label="创建时间" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="createBy" label="创建人" align="center" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <el-button v-hasPermi="['laypolicy:edit']" type="success" icon="edit" title="编辑"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button v-hasPermi="['laypolicy:delete']" type="danger" icon="delete" title="删除"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改政策对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">

          <!-- <el-col :lg="12">
            <el-form-item label="Id" prop="id">
              <el-input-number v-model.number="form.id" controls-position="right" placeholder="请输入Id" :disabled="title=='修改数据'"/>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :lg="12">
            <el-form-item label="层级" prop="level">
              <el-input v-model="form.level" placeholder="请输入层级" />
            </el-form-item>
          </el-col> -->
          <el-col :lg="24">
            <el-form-item label="父级id" prop="parentId">
              <el-cascader class="w100" :options="dataList"
                :props="{ checkStrictly: true, value: 'id', label: 'name', emitPath: false }" placeholder="请选择上级菜单"
                clearable v-model="form.parentId">
                <template #default="{ node, data }">
                  <span>{{ data.name }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option v-for="item in options.status " :key="item.dictValue" :value="item.dictValue"
                  :label="item.dictLabel"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="12">
            <el-form-item label="商家" prop="companyId">
              <el-select v-model="form.companyId" placeholder="请选择商家">
                <el-option v-for="item in  options.sql_company " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :lg="12">
            <el-form-item label="标题" prop="titile">
              <el-input v-model="form.titile" placeholder="请输入标题" />
            </el-form-item>
          </el-col> -->

          <el-col :lg="12">
            <el-form-item label="序号" prop="sort">
              <el-input type="number" v-model="form.sort" controls-position="right" placeholder="请输入序号" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="图标" prop="icon">
              <UploadImage v-model="form.icon" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col>
          <!-- 
          <el-col :lg="12">
            <el-form-item label="图片" prop="imageUrl">
              <UploadImage v-model="form.imageUrl" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col> -->



          <el-col :lg="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>



          <!-- <el-col :lg="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker v-model="form.updateTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新人" prop="updateBy">
              <el-input v-model="form.updateBy" placeholder="请输入更新人" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="laypolicy">
import {
  treelistLayPolicy, listLayPolicy,
  addLayPolicy, delLayPolicy, updateLayPolicy, getLayPolicy,
} from '@/api/business/laypolicy.js'

const { proxy } = getCurrentInstance()
const isExpandAll = ref(false)
const refreshTable = ref(true)
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

// 选中id数组数组
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'CreateTime',
  sortType: 'desc',
  name: undefined,
  companyId: undefined,
})
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
  {
    dictType: "status",
  }, {
    dictType: "sql_company",
  }
]

proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.dictType] = element.list
  })
})

function getList() {
  loading.value = true
  treelistLayPolicy(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      //dataList.value = res.data.result
      //total.value = res.data.totalNum
      dataList.value = res.data
      loading.value = false
    }
  })
    .catch(() => {
      loading.value = false
    })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1
  multiple.value = !selection.length;
}

// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref("")
// 操作类型 1、add 2、edit
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  form: {},
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "商家不能为空", trigger: "blur" }],
  },
  options: {
    // 状态id 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    status: [],
    // 状态名称 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    statusNameOptions: [],
    // 商家 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    company: [],
  }
})

const { form, rules, options } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  proxy.resetForm("formRef")
}

// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = '添加'
  opertype.value = 1
  form.value.status = '1'
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getLayPolicy(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = "修改数据"
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined && opertype.value === 2) {
        updateLayPolicy(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      } else {
        addLayPolicy(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy.$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
    .then(function () {
      return delLayPolicy(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}

// 导出按钮操作
function handleExport() {
  proxy
    .$confirm("是否确认导出政策数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      await proxy.downFile('/business/LayPolicy/export', { ...queryParams })
    })
}

handleQuery()
</script>